package com.firepongo.chaos.web.interceptor;

import com.firepongo.chaos.web.annotation.ManageLoginToken;
import com.firepongo.chaos.web.annotation.WxminiLoginToken;
import com.firepongo.chaos.model.dto.login.LoginUser;
import com.firepongo.chaos.web.interceptor.handler.AccessLimitLoginHandler;
import com.firepongo.chaos.web.interceptor.handler.ManageLoginHandler;
import com.firepongo.chaos.web.interceptor.handler.WxminiLoginHandler;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;

/**
 * @author G.G
 */
@Service
@Slf4j
public class AuthenticationInterceptor implements HandlerInterceptor {

    @Autowired
    private AccessLimitLoginHandler accessLimitLoginHandler;
    @Autowired
    private ManageLoginHandler manageLoginHandler;
    @Autowired
    private WxminiLoginHandler wxminiLoginHandler;

    @Override
    public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object object) throws Exception {
        if (!(object instanceof HandlerMethod)) {
            return true;
        }
        HandlerMethod handlerMethod = (HandlerMethod) object;
        Method method = handlerMethod.getMethod();

        //检查有没有需要用户权限的注解
        if (method.isAnnotationPresent(ManageLoginToken.class)) {
            boolean result = manageLoginHandler.handler(httpServletRequest, method);
            if (!result)
                return false;
        } else if (method.isAnnotationPresent(WxminiLoginToken.class)) {
            boolean result = wxminiLoginHandler.handler(httpServletRequest, method);
            if (!result)
                return false;
        }
        accessLimitLoginHandler.handler(httpServletRequest, method);

        return true;
    }

    @Override
    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {

    }

}
